package org.tnaggs.project.repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.tnaggs.project.model.Location;

public class LocationRepository implements GenericRepository<Location> {
	
	
	private JdbcTemplate template;
	
	public LocationRepository(JdbcTemplate template) {
		this.setTemplate(template);
	}

	public JdbcTemplate getTemplate() {
		return template;
	}

	public void setTemplate(JdbcTemplate template) {
		this.template = template;
	}

	@Override
	public Location findByID(int id) {
		return (Location)template.queryForObject("select * from Location where Location_ID = " + id, new LocationRowMapper());
	}
	
	@Override
	public List<Location> findAll() {
		return (List<Location>)template.query("select * from Location", new LocationRowMapper());
	}
	
	class LocationRowMapper implements RowMapper<Location> {

		@Override
		public Location mapRow(ResultSet rs, int arg1) throws SQLException {
		
				Location results = new Location();
				results.setLocationID(rs.getInt("Location_ID"));
				results.setContactID(rs.getInt("Contact"));
				results.setStreet(rs.getString("Street"));
				results.setCity(rs.getString("City"));
				results.setZipCode(rs.getInt("Zip_code"));
				return results;
		}

		
		
	}


	@Override
	public boolean insert(Location newVal) {
		int numResults = template.update("insert into Location (`Contact`,`Street`,`City`,`Zip_code`) values("  
				+ newVal.getContactID() + ",'" + newVal.getStreet() + "','" 
				+newVal.getCity() + "',"
				+newVal.getZipCode() + ")");
		return numResults == 1;
	}

	@Override
	public boolean delete(int id) {
		int numResults =  template.update("delete from Location where Location_ID = " + id);
		return numResults == 1;
	}

	@Override
	public boolean purge() {
      int numResults = template.queryForInt("select count(*) from Location;");
      int delResults = template.update("delete from Location;");
      return numResults == delResults;
	}
}
